package com.wireless.service;

/**
 * generate all command of chargeDevice,then you can write cmd to chargeDevice
 * @author fang.junpeng
 *
 */
public final class ChargeCmd {
	private ChargeCmd(){}
	
	public final static String cmd_charging = "charging";
	public final static String cmd_deviceID = "deviceID";
	private final static String cmd_startTAG = "ST";
	private final static String cmd_endTAG = "END" ;
	private final static String cmd_confirmCode = "confirmCode";
	private final static String cmd_completeCode = "completeCode";
	private final static String cmd_charge = "charge";
	
	/**
	 * generate the ChargeCode string
	 * @param minutes
	 * @return
	 */
	public static String getChargeCmd(int minutes){
		if(minutes<0 || minutes > 60){
			System.err.println("the minutes is higher than 60 or lower than 0");
			return "";
		}
		return getCmdLine(cmd_charge+minutes);
	}
	
	/**
	 * generate the confirmCode string
	 * @param code
	 * @return
	 */
	public static String getConfirmCodeCmd(int code){
		if(code<0){
			System.err.println("the confirm code is lower than 0");
			return null;
		}
		return getCmdLine(cmd_confirmCode+code);
	}
	
	/**
	 * decode the cmd from the chargeDevice,and return the code number
	 * @param cmd
	 * @return
	 */
	public static int getCmdCodeNum(String cmd) {
		int CodeNum = -1;
		String[] decodeResult = decodeCmd(cmd);
		if(null != decodeResult){
			try {
				CodeNum = Integer.parseInt(decodeResult[1]);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return CodeNum;
	}
	
	/**
	 * decode the cmd according the instruction set we designed
	 * @param cmd
	 * @return
	 */
	public static String[] decodeCmd(String cmd) {
		if(cmd == null || cmd.equals(""))
			return null;
		String[] decodeResult = null;
		decodeResult = cmd.split(",");
		if(decodeResult.length != 2 && null != decodeResult)
			return null;
		return decodeResult;
	}
	
	/**
	 * get device state from the cmd sended by the device
	 * the return must be the member of ChargeDeviceState
	 * @param cmd
	 * @return
	 */
	public static int getState(String cmd){
		int state = ChargeDeviceState.STATE_SEND_ID;
		String[] decodeResult = decodeCmd(cmd);
		if(decodeResult != null){
			String CmdString = decodeResult[0];
			if(cmd_deviceID.equals(CmdString))
				state = ChargeDeviceState.STATE_SEND_ID;
			if(cmd_confirmCode.equals(CmdString))
				state = ChargeDeviceState.STATE_COMPELETE;
			if(cmd_charging.equals(CmdString))
				state = ChargeDeviceState.STATE_CHARGING;
			if(cmd_completeCode.equals(CmdString))
				state = ChargeDeviceState.STATE_COMPELETE;
		}
		else
			return Integer.MAX_VALUE;
		return state;
	}
	
	private static String getCmd(String cmdContent){
		return cmd_startTAG+cmdContent + cmd_endTAG;
	}
	
	private static String getCmdLine(String cmdContent){
		return getCmd(cmdContent)+"\r\n";
	}
}
